package com.cedarhd.finance.msg.controller.api;

import com.cedarhd.finance.msg.common.JsonResult;
import com.cedarhd.finance.msg.common.ProcessAPI;
import com.cedarhd.finance.msg.controller.Routes;
import com.cedarhd.finance.msg.domain.entity.Point;
import com.cedarhd.finance.msg.domain.repository.specification.PointSpecification;
import com.cedarhd.finance.msg.domain.service.PointService;
import com.cedarhd.finance.msg.dto.PointBackendDTO;
import com.cedarhd.finance.msg.dto.PointDTO;
import com.cedarhd.finance.msg.dto.PointQueryDTO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Evan
 * @date 2018/3/26
 */
@Api(value = "埋点管理", description = "埋点管理")
@RestController
public class PointController {
    @Autowired
    private PointService pointService;

    @RequestMapping(value = Routes.POINT_SAVE,method = RequestMethod.POST)
    @ApiOperation(value = "新增埋点", notes = "新增埋点", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JsonResult save(HttpServletRequest request, @RequestBody PointDTO req){
        ProcessAPI api = (result, validate) -> {
            Point point = pointService.save(req);
            result.setResult(point);
        };
        return api.process(request);
    }

    @RequestMapping(value = Routes.POINT_LIST,method = RequestMethod.GET)
    @ApiOperation(value = "查询列表", notes = "查询列表", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public JsonResult<List<PointBackendDTO>> list(HttpServletRequest request, PointQueryDTO req){
        ProcessAPI api = (result, validate) -> {
            Specification<Point> spec = PointSpecification.buildFromDTO(req);
            Page<Point> pointPage = pointService.getRepository().findAll(spec,req.getPage());
            List<PointBackendDTO> dtoList = pointService.coverDTO(pointPage);
            result.setResult(dtoList);
            result.setSize(pointPage.getTotalElements());
        };
        return api.process(request);
    }

}
